<template>
  <div class="wrap">
    <div class='qr-code-wrapper'
         :style='{width: width + "px", height: height + "px"}'
         ref='qrCodeWrapper'>
    </div>
    <div :style='{width: width + "px", height: height + "px"}' class="mask"></div>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
export default {
  data () {
    return {
      qrCode: null
    }
  },
  props: {
    width: {
      type: Number,
      default: 200
    },
    height: {
      type: Number,
      default: 200
    },
    colorFront: {
      type: String,
      default: '#000'
    },
    colorBack: {
      type: String,
      default: '#fff'
    },
    url: {
      type: String,
      default: ''
    }
  },
  watch: {
    url (newV) {
      this.initQrCode()
    }
  },
  methods: {
    // 生成二维码
    initQrCode () {
      document.querySelector('.qr-code-wrapper').innerHTML = ''
      this.$nextTick(() => {
        this.qrCode = new QRCode(this.$refs.qrCodeWrapper, {
          text: this.url,
          width: this.width,
          height: this.height,
          colorDark: this.colorFront, // 前景色
          colorLight: this.colorBack, // 背景色
          correctLevel: QRCode.CorrectLevel.L // 容错率级别 L M Q H
        })
      })
    },
    // 下载二维码
    downloadQrImg () {
      if (this.qrCode) {
        // 生成二维码 base64
        html2canvas(this.$refs.qrCodeWrapper, {
          backgroundColor: null,
          width: this.width,
          height: this.height
        }).then(canvas => {
          var imgData = canvas.toDataURL('image/jpeg')
          // 下载图片
          let elink = document.createElement('a')
          elink.download = '会议二维码'
          elink.style.display = 'none'
          elink.href = imgData
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        })
      }
    }
  },
  mounted () {
    this.initQrCode()
  }
}
</script>

<style lang="stylus" scoped>
.wrap
  position relative
  .mask
    position absolute
    top 0
    left 0
    width 100%
    height 100%
    z-index 100
.qr-code-wrapper
  position relative
  img
    width 100%
</style>
